package bim.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	
	 String defaultFailureUrl;
	 boolean forwardToDestination = false;
	 RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	 
	@Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {

        if (defaultFailureUrl == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户认证失败: " + exception.getMessage());
        } else {
            saveException(request, exception);
            if (forwardToDestination) {
                request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
            } else {
                redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
            }
        }
    }
    
    /**
     * The URL which will be used as the failure destination.
     *
     * @param defaultFailureUrl the failure URL, for example "/loginFailed.jsp".
     */
    public void setDefaultFailureUrl(String defaultFailureUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl),
                "'" + defaultFailureUrl + "' is not a valid redirect URL");
        this.defaultFailureUrl = defaultFailureUrl;
    }


}